package cc.wanforme.st.server.util.encryt;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Base64.Decoder;
import java.util.Base64.Encoder;

/** 加密工具
 * @author wanne
 * @date 2022-04-12
 */
public class Base64Tool {
	private static Charset CHARSET = StandardCharsets.UTF_8;
	private static Encoder encoder64 = Base64.getEncoder();
	private static Decoder decoder64 = Base64.getDecoder();
	
	
	/** base64 字符串到字符串编码
	 * @param raw
	 * @return
	 */
	public static String encodeBase64(String raw) {
		byte[] bytes = raw.getBytes(CHARSET);
		String encodedStr = encoder64.encodeToString(bytes);
		return encodedStr;
	}
	
	/** base64 字符串到字符串解码
	 * @param encodedStr
	 * @return
	 */
	public static String decodeBase64(String encodedStr) {
		byte[] decodeBs = decoder64.decode(encodedStr);
		String re = new String(decodeBs, CHARSET);
		return re;
	}
	
	/** 先取反，再 base64 编码
	 * @param raw
	 * @return
	 */
	public static String encodeResData(String raw) {
		// 1. 原生字符串字节
		byte[] bytes = raw.getBytes(CHARSET);
//		System.out.println("origin-bytes: " + Arrays.toString(bytes));
		
		// 2. 原生字节取反操作
		byte[] reversedBs = new byte[bytes.length];
		for(int i=0; i<bytes.length; i++) {
			reversedBs[i] = (byte) ~(bytes[i]);
		}
//		System.out.println("reverse-bytes: " + Arrays.toString(reversedBs));
		
		// 3. 编码
		//String encodedStr = encoder64.encodeToString(reversedBs);
		byte[] encodedBs = encoder64.encode(reversedBs);
		return new String(encodedBs, CHARSET);
	}

	/** “先取反，再 base64 编码” 的解码
	 * @param encodedStr
	 * @return
	 */
	public static String decodeResData(String encodedStr) {
		// 1. 解码
		byte[] encodedBs = encodedStr.getBytes(CHARSET);
		byte[] decodeReversedBs = decoder64.decode(encodedBs);
		// 2. 字节取反
		byte[] bytes = new byte[decodeReversedBs.length];
		for(int i=0; i<decodeReversedBs.length; i++) {
			bytes[i] = (byte) ~(decodeReversedBs[i]);
		}
		// 3. 结果
		String re = new String(bytes, CHARSET);
		return re;
	}
	
	public static String encodeReqData(String raw) {
		return encodeResData(raw);
	}
	
	public static String decodeReqData(String encodedStr) {
		return decodeResData(encodedStr);
	}

	
	public static void main(String[] args) {
//		String abc = "01234567890";
//		String encodeBase64 = encodeBase64(abc);
//		String decodeBase64 = decodeBase64(encodeBase64);
//		System.out.println("Base64-encode: " + encodeBase64);
//		System.out.println("Base64-decode: " + decodeBase64);
//		System.out.println("======================");
		
		String abc2 = "01234567890";
		String encodeBase642 = encodeResData(abc2);
		String decodeBase642 = decodeResData(encodeBase642);
		System.out.println("Base64-2-encode: " + encodeBase642);
		System.out.println("Base64-2-decode: " + decodeBase642);
		System.out.println("======================");
		
		System.out.println("Base64-3-encode: " + decodeReqData("zs3M"));
		System.out.println("Base64-3-encode: " + decodeReqData("iJ6R"));
		
	}
	
}